package com.wingsfrog.travel.controller.filter;

import com.wingsfrog.travel.modules.entity.User;
import com.wingsfrog.travel.service.UserService;
import com.wingsfrog.utils.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class CheckTokenInterceptorAdapter extends HandlerInterceptorAdapter {
    @Autowired
    UserService userService;

    private static Logger logger = LoggerFactory.getLogger(CheckTokenInterceptorAdapter.class);

    private List<String> passUrls;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info(request.getRequestURI());
        String token = request.getHeader("travel-authorization");
        if (token == null) return false;
        User user = userService.findUserByToken(token);
        if (user == null) return false;
        request.getSession().setAttribute(SessionUtil.USER_ID, user.getId());
        return true;
    }

    public List<String> getPassUrls() {
        return passUrls;
    }

    public void setPassUrls(List<String> passUrls) {
        this.passUrls = passUrls;
    }
}
